'''
Descripttion: 
Author: QYJ
version: 
Date: 2022-08-24 15:20:44
LastEditors: QYJ
LastEditTime: 2022-09-01 15:42:34
'''

import os
from pathlib import Path
import subprocess
import json

SCRIPT_DIR_PATH = Path(__file__).parent / '..\\scripts'

SCRIPT_DEFAULT_NAME = '\\main.pyw'


class Script:
    def __init__(self, file_path, script_name) -> None:
        self.file_path = file_path
        self.script_name = script_name
        self.params = []
        self.get_param()

    def run(self, *params):
        script_list = ['python', self.file_path+SCRIPT_DEFAULT_NAME]
        for i in params[0]: 
            script_list.append(i)
        return subprocess.check_output(script_list, shell=False).decode('gbk')

    def get_param(self):
        with open (rf'{self.file_path}\\config.json', 'r' , encoding='utf-8') as fp:
            self.params = json.load(fp)['params'].values()



class ScriptManager:
    def __init__(self) -> None:
        self._scripts = {}
        self.init_scripts()

    def get_script_names(self):
        return list(self._scripts.keys())

    def get_script_params(self):
        params = {}
        for key, val in self._scripts.items():
            params[key] = list(val.params)
        return params

    def init_scripts(self):
        for root, dir, _ in os.walk(SCRIPT_DIR_PATH):
            for i in dir:
                try:
                    script = Script(root+'\\'+i, i)
                    self._scripts[i] = script
                except Exception as E:
                    pass
            break

    def run_script(self, script_name, *script_params):
        return self._scripts[script_name].run(script_params[0])

    def get_script_name_info(self, name, key):
        return(vars(self._scripts[name])[key])

